//
//  GYXOAuthViewController.swift
//  GYXWeibo
//
//  Created by Twisal on 2017/3/2.
//  Copyright © 2017年 Twisal. All rights reserved.
//

import UIKit
import SVProgressHUD

class GYXOAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    override func loadView() {
        view = webView
        view.backgroundColor = UIColor.white
        title = "微博授权登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFill))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupWeiboOAuthView()
    }

    private func setupWeiboOAuthView() {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectUri)"
        guard let url = URL(string: urlString)else {
            
            return
        }
        let request = URLRequest(url: url)
        webView.loadRequest(request)
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
    }
    
    /// 监听naviBar左边按钮
    @objc fileprivate func close() {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    /// 监听naviBar右边按钮
    @objc private func autoFill() {
//        let js = "document.getElementById('userId').value = 'gaoyx412@sina.com';"+"document.getElementById('passwd').value = '13932054553gao';"
        let js = "document.getElementById('userId').value = '251292977@qq.com';"+"document.getElementById('passwd').value = '13932054553gao';"
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension  GYXOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 1,判断请求是否有回调页
        print("加载请求---\(request.url?.absoluteString)")
        if request.url?.absoluteString.hasPrefix(WBRedirectUri) == false {
            return true
        }
        
        // 2,判断是否有参数
        print("加载请求---\(request.url?.query)")
        let codePrefix = "code="
        if request.url?.query?.hasPrefix(codePrefix) == false {
            close()
            return false
        }
        
        // 3,获取授权码
        let code = request.url?.query?.substring(from: codePrefix.endIndex) ?? ""
        print("获取到的授权码\(code)")
        
        GYXNetworkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "网络请求失败")
            } else {
                SVProgressHUD.showInfo(withStatus: "登录成功")
                // 发送通知
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
                // 关闭授权成功等待页面
                self.close()
            }
        }
        // 不需要调到百度就return false
        return false
    }
}
